package com.haiyi.software.app;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Environment;
import android.util.Log;

import com.alipay.android.app.sdk.R.color;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.haiyi.software.app.R.layout;
import com.haiyi.software.app.R.string;
import com.haiyi.software.app.basic.MainApplicationBasic;
import com.haiyi.software.entity.UserInfo;
import com.haiyi.software.tools.MyTools;
import com.haiyi.software.xmpp.event.XMPPConnectionStateEvent;
import com.haiyi.software.xmpp.event.XMPPEvent;
import com.haiyi.software.xmpp.event.XMPPStream;
import com.haiyi.software.xmpp.service.HIChatServices;
import com.loopj.android.http.AsyncHttpClient;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.L;

public class MainApplication extends MainApplicationBasic {

	public final static String VERSION = "v1.0.2.140803";

	private int ScreenWidth;

	public void setScreenWidth(int screenWidth) {
		ScreenWidth = screenWidth;
	}

	public int getScreenWidth() {
		return ScreenWidth;
	}

	private static String ServerIP;

	public String getServerIP() {
		return ServerIP;
	}

	public void setServerIP(String serverIP) {
		ServerIP = serverIP;
	}

	private ArrayList<XMPPEvent> mXMPPEvent;

	private ArrayList<XMPPConnectionStateEvent> mXMPPConnEvent;

	public ArrayList<XMPPConnectionStateEvent> getmXMPPConnEvent() {
		return mXMPPConnEvent;
	}

	private static MainApplication mApplication;

	private static AsyncHttpClient asyncHttpClient;

	public AsyncHttpClient getAsyncHttpClient() {

		if (asyncHttpClient == null) {

			asyncHttpClient = new AsyncHttpClient();

		}
		return asyncHttpClient;
	}

	/**
	 * 我的个人信息
	 */
	private static UserInfo mineUserInfo = null;

	public UserInfo getMineUserInfo() {
		if (mineUserInfo == null) {
			mineUserInfo = new UserInfo();
		}
		return mineUserInfo;
	}

	public void setMineUserInfo(UserInfo u) {
		this.mineUserInfo = u;
	}

	public String getAppDirectory() {
		return AppDirectory;
	}

	public String getAppFaceDirectory() {
		return AppFaceDirectory;
	}

	private String AppDirectory;

	private String AppFaceDirectory;

	private String AppVoiceDirectory;

	private String AppImageDirectory;

	private String AppImageThumbDirectory;

	private String appApkDirectory;

	public String getAppImageDirectory() {
		return AppImageDirectory;
	}

	public String getAppImageThumbDirectory() {
		return AppImageThumbDirectory;
	}

	public String getAppVoiceDirectory() {
		return AppVoiceDirectory;
	}

	/**
	 * 表情集合
	 */
	private Map<String, Integer> mFaceMap = new LinkedHashMap<String, Integer>();

	/**
	 * GIF集合
	 */
	private Map<String, List<Map<String, String>>> mGifMap = new LinkedHashMap<String, List<Map<String, String>>>();

	/**
	 * GIF集合
	 */
	public Map<String, List<Map<String, String>>> getmGifMap() {
		return mGifMap;
	}

	/**
	 * 头像菜单集合
	 */
	private Map<String, String> mFaceBarMap = new LinkedHashMap<String, String>();

	/**
	 * 头像菜单集合
	 */
	public Map<String, String> getmFaceBarMap() {
		return mFaceBarMap;
	}

	// public void setmFaceBarMap(Map<String, String> mFaceBarMap) {
	// this.mFaceBarMap = mFaceBarMap;
	// }

	public static int NUM = 20;// 每页20个表情,还有最后一个删除button
	public static final int NUM_PAGE = 5;// 总共有多少页

	private HiChat hiChat;

	public HiChat getHiChat() {
		return hiChat;
	}

	public void setHiChat(HiChat hiChat) {
		this.hiChat = hiChat;
	}

	public synchronized static MainApplication getInstance() {
		return mApplication;
	}

	public Map<String, Integer> getFaceMap() {
		if (!mFaceMap.isEmpty())
			return mFaceMap;
		return null;
	}

	public synchronized void removeXMPPEvent(XMPPEvent args) {
		mXMPPEvent.remove(args);
	}

	public synchronized void addXMPPEvent(XMPPEvent args) {
		mXMPPEvent.add(args);
	}

	private XMPPStream mXMPPStream;

	public XMPPStream getmXMPPStream() {
		return mXMPPStream;
	}

	public void setmXMPPStream(XMPPStream mXMPPStream) {
		this.mXMPPStream = mXMPPStream;
	}

	public Map<String, Object> applicationHashtable;

	@Override
	public void onCreate() {

		// TODO 自动生成的方法存根
		super.onCreate();

		L.writeLogs(false);
		L.writeDebugLogs(false);

		com.haiyi.software.tools.L.isDebug = false;

		mApplication = this;

		initHashTable();

		intPath();

		initFaceMap();

		initGifMap();

		// Log.i("gifMap", getmGifMap().get("1").toString());

		initImageLoader(getApplicationContext());

		mXMPPEvent = new ArrayList<XMPPEvent>();

		mXMPPConnEvent = new ArrayList<XMPPConnectionStateEvent>();

	}

	private void initHashTable() {

		// TODO 自动生成的方法存根
		applicationHashtable = new Hashtable<String, Object>();

	}

	private void intPath() {
		if (hasSdcard()) {

			this.AppDirectory = Environment.getExternalStorageDirectory()
					.getPath()
					+ "/"
					+ getResources().getString(R.string.AppDirectory);

			this.AppFaceDirectory = Environment.getExternalStorageDirectory()
					.getPath()
					+ "/"
					+ getResources().getString(R.string.AppDirectory)
					+ "/"
					+ getResources().getString(R.string.AppFaceDirectory);

			this.AppVoiceDirectory = Environment.getExternalStorageDirectory()
					.getPath()
					+ "/"
					+ getResources().getString(R.string.AppDirectory)
					+ "/"
					+ getResources().getString(R.string.AppVoiceDirectory);

			this.AppImageDirectory = Environment.getExternalStorageDirectory()
					.getPath()
					+ "/"
					+ getResources().getString(R.string.AppDirectory)
					+ "/"
					+ getResources().getString(R.string.AppImageDirectory);

			com.haiyi.software.tools.L
					.i("AppImageDirectory", AppImageDirectory);

			this.AppImageThumbDirectory = Environment
					.getExternalStorageDirectory().getPath()
					+ "/"
					+ getResources().getString(R.string.AppDirectory)
					+ "/"
					+ getResources().getString(R.string.AppImageThumbDirectory);

			this.appApkDirectory = Environment.getExternalStorageDirectory()
					.getPath()
					+ "/"
					+ getResources().getString(R.string.AppDirectory)
					+ "/"
					+ getResources().getString(R.string.AppApkDirectory);

			File rootFile = new File(this.AppDirectory);
			if (!rootFile.exists()) {
				rootFile.mkdir();
			}

			File facefile = new File(this.AppFaceDirectory);

			if (!facefile.exists()) {
				facefile.mkdir();
			}

			File voiceFile = new File(this.AppVoiceDirectory);
			if (!voiceFile.exists()) {
				voiceFile.mkdir();
			}

			File imageFile = new File(this.AppImageDirectory);
			if (!imageFile.exists()) {
				imageFile.mkdir();
			}

			File thumbFile = new File(this.AppImageThumbDirectory);
			if (!thumbFile.exists()) {
				thumbFile.mkdir();
			}
			File apkFile = new File(this.appApkDirectory);
			if (!apkFile.exists()) {
				apkFile.mkdir();
			}
		}

	}

	/**
	 * 1、判断SD卡是否存在
	 */
	private static boolean hasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public static void initImageLoader(Context context) {

		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	public synchronized void XMPPConnectEvent(XMPPConnection connection) {

	}

	public synchronized void XMPPAuthenticate(XMPPConnection connection) {
		for (XMPPEvent event : mXMPPEvent) {
			event.XMPPAuthenticate(getmXMPPStream().GetXMPPConnection());
		}
	}

	public synchronized void XMPPNotAuthenticate(XMPPConnection connection) {

	}

	public synchronized void XMPPReceiveMessage(Message msg) {

		showNotification(msg);

		for (XMPPEvent event : mXMPPEvent) {
			event.XMPPReceiveMessage(msg);
		}

	}

	private void initFaceMap() {

		String str_file;
		try {
			str_file = MyTools.getStringFromInputStream(getResources()
					.openRawResource(R.raw.expression));

			JsonParser parser = new JsonParser();
			JsonArray ary = parser.parse(str_file).getAsJsonArray();

			int id = 0;

			for (int i = 0; i < ary.size(); i++) {

				id = getResources()
						.getIdentifier(
								ary.get(i).getAsJsonObject().get("sface")
										.getAsString(), "raw", getPackageName());

				mFaceMap.put(ary.get(i).getAsJsonObject().get("str")
						.getAsString(), id);
			}
			// Log.i("faceMap", mFaceMap.toString());
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return;
		}

	}

	private void initGifMap() {
		String json_file = MyTools.getStringFromInputStream(getResources()
				.openRawResource(R.raw.per_face_json));
		JsonParser parser = new JsonParser();
		JsonArray ary = parser.parse(json_file).getAsJsonArray();

		Resources res = getResources();

		for (int i = 0; i < ary.size(); i++) {

			mFaceBarMap.put(ary.get(i).getAsJsonObject().get("key")
					.getAsString(), ary.get(i).getAsJsonObject().get("string")
					.getAsString());

			String fileName = ary.get(i).getAsJsonObject().get("file")
					.getAsString();

			if (!fileName.equals("expression")) {

				try {

					int file_id = res.getIdentifier(fileName, "raw",
							getPackageName());

					String json_str = MyTools
							.getStringFromInputStream(getResources()
									.openRawResource(file_id));

					List<Map<String, String>> gifList = new ArrayList<Map<String, String>>();

					// com.haiyi.software.tools.L.d("json_str", json_str);

					JsonParser parser_gif = new JsonParser();

					JsonArray ary_gif = parser_gif.parse(json_str)
							.getAsJsonArray();

					for (int j = 0; j < ary_gif.size(); j++) {

						Map<String, String> mg = new Hashtable<String, String>();

						mg.put("string",
								ary_gif.get(j).getAsJsonObject().get("string")
										.getAsString());
						mg.put("name",
								ary_gif.get(j).getAsJsonObject().get("name")
										.getAsString());
						gifList.add(mg);
					}
					mGifMap.put(ary.get(i).getAsJsonObject().get("key")
							.getAsString(), gifList);

					Log.d("mGIFMAP<<<<<<<<<<<<>>>>>>>>>>>>", mGifMap.toString());

				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}

		}

		// Log.d("jsonfile", json_file);
	}

	public String getAppApkDirectory() {
		return appApkDirectory;
	}

	public void setAppApkDirectory(String appApkDirectory) {
		this.appApkDirectory = appApkDirectory;
	}
}
